<?php

namespace backend\modules\login\controllers;
use backend\component\BackendBaseController;
use backend\component\ResultFormat;
use backend\models\LoginForm;
use backend\models\SignupForm;
use common\component\XxteaD;
use backend\utils\JwtUtil;

class LoginController extends BackendBaseController
{
    public $enableCsrfValidation = false;
    public $layout = "/login";
    public function actions()
    {
        return [
            'captcha' => [
                'class' => 'common\component\CaptchaI',
                'maxLength' => 4,
                'minLength' => 4,
                'height'=> 40,
                'width'=> 80,
                'imageLibrary'=> 'gd',
                'foreColor' => 0x2eaeff,
            ]
        ];
    }

    public function actionLoginPost() {
        $model = new LoginForm();
        $postData = \Yii::$app->request->post();
        //解密密码
        $csrfBackendToken = $postData['csrf_token'];
        $paost =[];
        $paost['LoginForm']['password'] = $postData['password'];
        $paost['LoginForm']['username'] = $postData['username'];
        $encryptPassword = trim($postData['password']);
        $paost['LoginForm']['password'] = XxteaD::decrypt($encryptPassword,$csrfBackendToken);
       // var_dump($paost);
       // die();
        if ($model->load($paost) && $model->login()) {
            $payload_test=array('iss'=>'admin','iat'=>time(),'exp'=>time()+3600 * 24 * 30,'nbf'=>time(),'sub'=>'www.admin.com','jti'=>md5(uniqid('JWT').time()));;
            $token_test= JwtUtil::getToken($payload_test);

            return ResultFormat::success("登录成功",["token"=>$token_test,"name"=>$model->username,"uuid"=>'']);
        }else{
            return ResultFormat::error($model->getErrorsToString());
        }
    }
     public function actionDoRegister(){
         $post = \Yii::$app->request->post();
         $model = new SignupForm();
         $model->load($post,"");
        // $model->csrf_token = \Yii::$app->params['privateKey'];//\Yii::$app->request->getCsrfToken();//!isset($post["_csrf-frontend"])?"":$post["_csrf-frontend"];
         if ($model->signup()) {
             return ResultFormat::success("注册成功");
         }
         return ResultFormat::error($model->getErrorsToString());
     }

    public function actionLogout() {
        if (\Yii::$app->user->getIsGuest()) {
            return $this->goHome();
        }
        \Yii::$app->user->logout();
        return $this->goHome();
    }


}
